package com.lx.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lx.dao.CategoryDao;
import com.lx.entity.Category;
import com.lx.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public PageInfo<Category> getPageInfo(Map<String, Object> params) {
        int pageNum = 1;
        int pageSize = 5;

        if (params.containsKey("pageNum")) {
            pageNum = Integer.parseInt(params.get("pageNum").toString());
        }
        if (params.containsKey("pageSize")) {
            pageSize = Integer.parseInt(params.get("pageSize").toString());
        }

        // 使用 PageHelper 进行分页
        PageHelper.startPage(pageNum, pageSize);
        List<Category> categoryList = categoryDao.selectByPage(params);

        // 封装分页结果
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        return pageInfo;
    }

    @Override
    public List<Category> getAllCategories() {
        return categoryDao.selectAll();
    }

    @Override
    public List<Category> getFirstLevelCategories() {
        return categoryDao.selectByType(1, null);
    }

    @Override
    public List<Category> getSecondLevelCategories(Integer id) {
        return categoryDao.selectByType(2, id);
    }

    @Override
    public List<Category> getThirdLevelCategories(Integer id) {
        return categoryDao.selectByType(3, id);
    }

    @Override
    public Category getCategoryById(Integer id) {
        return categoryDao.selectById(id);
    }

    @Override
    public boolean addCategory(Category category) {
        if (hasSameNameInSameLevel(category)) {
            return false;
        }
        return categoryDao.insert(category);
    }

    @Override
    public boolean updateCategory(Category category) {
        return categoryDao.update(category);
    }

    @Override
    public boolean deleteCategory(Integer id) {
        int count = categoryDao.hasUsed(id);
        if (count > 0) {
            return false;
        }
        return categoryDao.delete(id);
    }

    @Override
    public int selectSameName(Integer type, String name) {
        return categoryDao.selectCountByName(name, type);
    }

    private boolean hasSameNameInSameLevel(Category category) {
        return categoryDao.selectAll().stream()
                .anyMatch(c -> c.getType().equals(category.getType())
                        && c.getName().equals(category.getName()) //下面这行可以去掉，要新增的分类貌似还没有id...
                        && !c.getId().equals(category.getId()));
    }
}
